package com.platform.api;

import com.platform.annotation.LoginUser;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.utils.*;
import com.platform.utils.push.UPush;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 朱如森
 */
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends ApiBaseAction {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ApiOrderService apiOrderService;
    @Autowired
    private ApiAmountBillService apiAmountBillService;

    /**
     * 新增订单
     *
     * @param loginUser
     * @param zbUserId  主播id
     * @param mouldId   类型 1 一对一 4旅游向导
     * @param num       数量
     * @param price     单价
     * @param total     总价
     * @param remark    备注
     * @param time      预约时间
     * @return
     */
    @RequestMapping("/add")
    public R add(@LoginUser UserVo loginUser, Long zbUserId, Long mouldId, Integer num, BigDecimal price, BigDecimal total, String remark, String time) {
        try {
            if (mouldId != 1L) {
                return R.ok(1, "服务升级中,敬请期待", "");
            }

            UserVo userVo = apiUserService.queryObject(loginUser.getId());
            UserVo zbUser = apiUserService.queryObject(zbUserId);


            String mouldName = "";
            String name = "";
            if (mouldId == 1L) {
                mouldName = "一对一视频";
                name = "live";
            }
            if (mouldId == 2L) {
                mouldName = "情感咨询";
                name = "emotion";
            }
            if (mouldId == 3L) {
                mouldName = "叫醒服务";
                name = "wake";
            }
            if (mouldId == 4L) {
                mouldName = "旅游向导";
                name = "guide";
            }
            if (userVo != null) {


                /**
                 * 扣除费用
                 */
                if (total != null) {
                    apiAmountBillService.orderConsume(IdUtil.createIdbyUUID(), zbUserId, name, total, userVo);
                }
                /**
                 * 插入订单
                 */
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                ApiOrderVo apiOrderVo = new ApiOrderVo();
                apiOrderVo.setZbUserId(zbUserId);
                apiOrderVo.setCreateDate(new Date());
                apiOrderVo.setCmUserId(loginUser.getId());
                apiOrderVo.setNum(num);
                apiOrderVo.setPrice(price);
                apiOrderVo.setTotal(total);
                apiOrderVo.setRemark(remark);
                apiOrderVo.setTime(df.parse(time));
                /**
                 * 状态 1未处理、2处理中、3已处理
                 */
                apiOrderVo.setStatus(1);
                apiOrderVo.setMouldId(mouldId);
                apiOrderVo.setMouldName(mouldName);
                apiOrderService.save(apiOrderVo);
                userVo = apiUserService.queryObject(loginUser.getId());
            }

            /**
             * 推送
             */
            UPush.push(zbUser.getMobile_type(), zbUser.getDevice_token(), "预约成功", "预约主播成功，请尽快处理订单");
            return R.ok(0, "提交成功", userVo.getAvailable_amount().stripTrailingZeros().toPlainString());
        } catch (ParseException e) {
            e.printStackTrace();
            return R.ok(12, "系统异常", "");
        }
    }

    /**
     * 会员 订单列表
     *
     * @param loginUser
     * @param type      1已预约 2 进行中 3 未评价 4已评价
     * @param page
     * @return
     */
    @RequestMapping("/listCm")
    public R listCm(@LoginUser UserVo loginUser,
                    @RequestParam(value = "type", defaultValue = "1") Integer type,
                    @RequestParam(value = "page", defaultValue = "1") Integer page) {
        Map params = new HashMap();
        params.put("page", page);
        params.put("limit", 10);
        params.put("sidx", "create_date");
        params.put("order", "desc");

        if (type == 3) {
            params.put("status", 3);
            params.put("commentStatus", 2);
        } else if (type == 4) {
            params.put("status", 3);
            params.put("commentStatus", 1);
        } else {
            params.put("status", type);
        }
        params.put("cmUserId", loginUser.getId());

        Query query = new Query(params);


        List<ApiOrderVo> list = apiOrderService.queryList(query);
        List<Map<String, Object>> reObject = new ArrayList<>();

        for (ApiOrderVo info : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", info.getId());
            map.put("time", info.getTime());
            map.put("remark", info.getRemark());
            map.put("mouldId", info.getMouldId());
            map.put("mouldName", info.getMouldName());
            UserVo userVo = apiUserService.queryObject(info.getZbUserId());
            if (userVo != null) {
                UserInfo userInfo = new UserInfo();
                userInfo.setNickName(userVo.getNickname());
                userInfo.setOnlineStatus(userVo.getOnline_status());
                userInfo.setAvatar(userVo.getAvatar());
                userInfo.setId(userVo.getId());
                map.put("zbUser", userInfo);
            }

            reObject.add(map);
        }

        return R.ok(0, "获取成功", reObject);
    }


    /**
     * 主播 订单列表
     *
     * @param loginUser
     * @param status    1未处理、2处理中、3已处理
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public R list(@LoginUser UserVo loginUser,
                  @RequestParam(value = "status", defaultValue = "1") Integer status,
                  @RequestParam(value = "page", defaultValue = "1") Integer page) {
        Map params = new HashMap();
        params.put("page", page);
        params.put("limit", 10);
        params.put("sidx", "create_date");
        params.put("order", "desc");
        if (status != null) {
            params.put("status", status);
        }
        params.put("zbUserId", loginUser.getId());

        Query query = new Query(params);
        List<ApiOrderVo> list = apiOrderService.queryList(query);

        List<Map<String, Object>> reObject = new ArrayList<>();

        for (ApiOrderVo info : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", info.getId());
            map.put("time", info.getTime());
            map.put("remark", info.getRemark());
            map.put("mouldId", info.getMouldId());
            map.put("mouldName", info.getMouldName());
            UserVo userVo = apiUserService.queryObject(info.getCmUserId());
            if (userVo != null) {
                UserInfo userInfo = new UserInfo();
                userInfo.setNickName(userVo.getNickname());
                userInfo.setAvatar(userVo.getAvatar());
                userInfo.setId(userVo.getId());
                userInfo.setMobile(userVo.getMobile());
                userInfo.setAvailableAmount(userVo.getAvailable_amount());
                map.put("cmUser", userInfo);
            }

            reObject.add(map);
        }

        return R.ok(0, "获取成功", reObject);
    }

    /**
     * 编辑
     *
     * @param loginUser
     * @param id
     * @param status    状态 1未处理、2处理中、3已处理
     * @return
     */
    @RequestMapping("/edit")
    public R edit(@LoginUser UserVo loginUser, Long id, Integer status) {
        ApiOrderVo apiOrderVo = apiOrderService.selectOne(id);

        UserVo userVo = apiUserService.queryObject(apiOrderVo.getCmUserId());

        if (apiOrderVo.getStatus() != 3) {
            if (apiOrderVo != null) {
                if (apiOrderVo.getStatus() == 4) {
                    apiOrderService.del(id);
                    return R.ok(2, "用户已经取消预约", "");
                }
                apiOrderVo.setStatus(status);
            }
            apiOrderService.updata(apiOrderVo);

            if (status != null && status == 3 && apiOrderVo.getTotal() != null) {
                /**
                 * 给主播钱
                 */
                apiAmountBillService.orderConsumeEnd(apiOrderVo.getZbUserId(), apiOrderVo.getMouldName(), apiOrderVo.getTotal(), userVo);
            }
        }


        return R.ok(0, "提交成功", "");
    }

    /**
     * 取消
     *
     * @param loginUser
     * @param id
     * @return
     */
    @RequestMapping("/delBespeak")
    public R delBespeak(@LoginUser UserVo loginUser, Long id) {

        ApiOrderVo apiOrderVo = apiOrderService.selectOne(id);
        if (apiOrderVo != null) {
            if (apiOrderVo.getStatus() != 1) {
                return R.ok(1, "预约已接单，暂时无法取消", "");
            }
            apiOrderVo.setStatus(4);
            apiOrderService.updata(apiOrderVo);

            /**
             * 返回钱到账户中
             */
            UserVo userVo = apiUserService.queryObject(apiOrderVo.getCmUserId());
            apiUserService.recharge(userVo, "add", apiOrderVo.getTotal());
            /**
             * 添加账单记录
             */

            ApiAmountBillVo apiAmountBillVo = new ApiAmountBillVo();

            apiAmountBillVo.setCreateTime(new Date());
            apiAmountBillVo.setMouldId(apiOrderVo.getZbUserId());
            apiAmountBillVo.setAmount(apiOrderVo.getTotal());
            apiAmountBillVo.setUserId(apiOrderVo.getZbUserId());
            apiAmountBillVo.setTitle("取消订单返还");
            apiAmountBillVo.setMouldName(apiOrderVo.getMouldName());
            apiAmountBillVo.setStatus(3);
            apiAmountBillVo.setType(2);
            apiAmountBillService.save(apiAmountBillVo);


            userVo = apiUserService.queryObject(loginUser.getId());

            return R.ok(0, "成功取消预约", userVo.getAvailable_amount().stripTrailingZeros().toPlainString());
        }
        return R.ok(0, "已成功取消预约", loginUser.getAvailable_amount().stripTrailingZeros().toPlainString());
    }


}
